package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession httpSession){
        //获取用户名
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        //mp的方法,查询用户名是否存在
        Employee one = employeeService.getOne(qw);//where username=?
        if(one==null){
            return R.error("用户名不存在");
        }


        String rowPwd = employee.getPassword();//明文 123456
        String dbPwd = one.getPassword();//密文 rqwrwrwe532154
        //把明文加密成密文
        String pwd = DigestUtils.md5DigestAsHex(rowPwd.getBytes()); // 123456->rqwrwrwe532154
        //比较
        if (!dbPwd.equals(pwd)){
            return R.error("密码错误");
        }
        Integer status = one.getStatus();
        if (status==0){
            return R.error("员工已禁用");
        }

        //存储用户对象
        httpSession.setAttribute("loginEmployee", one); //存入session中以键值对的形式存,key="loginEmployee" ,值 one 对象
        one.setPassword(null);//密码不要返回
        return R.success(one);//返回


    }
    //退出功能
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        request.getSession().removeAttribute("loginEmployee");//这里的key="loginEmployee"
        return R.success("退出成功");
    }

    //新增员工
    @PostMapping
    public R save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工，员工信息：{}",employee.toString());
        //这里的信息是前端之外要添加的数据
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //设置创建时间和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户的id
//        Employee loginEmployee = (Employee) request.getSession().getAttribute("loginEmployee");//从对象中获取id
//        Long id = loginEmployee.getId();

        //添加创建人和修改人
//        employee.setCreateUser(id);
//        employee.setUpdateUser(id);

        boolean save = employeeService.save(employee);

        return save?R.success("新增员工成功"):R.error("新增员工失败");

    }
    //分页查询
    @GetMapping("/page")
    public R page(int page, int pageSize, String name){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize,name);
        //构造分页构造器,这里是mp里提供的方法
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件,like模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件,按更新时间排序
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }
    //禁用,启用员工账号
    @PutMapping
    public R update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        //获取session里的one对象( key=loginEmployee 值 one对象) 要更新人的id
        Employee loginEmployee = (Employee) request.getSession().getAttribute("loginEmployee");
        //获取one对象里的id
        Long id = loginEmployee.getId();
        //设置更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //设置更新人
        employee.setUpdateUser(id);
        //调用mp里的更新方法 禁用 启用实际上也就是更新数据库的status
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }
    //修改员工信息
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        log.info("根据id查询员工信息...");

        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }

}
